﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Unity;

namespace Bricks.Unity.Injecting
{

    /// <summary>
    /// 
    /// </summary>
    public static class UnityContainerExtensions
    {

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TLifetimeManager"></typeparam>
        /// <param name="unityContainer"></param>
        public static void EndLifetime<TLifetimeManager>(this IUnityContainer unityContainer) where TLifetimeManager : LifetimeManager
        {
            IEnumerable<TLifetimeManager> lifetimeManagers = unityContainer.Registrations.Select(containerRegistration => containerRegistration.LifetimeManager).OfType<TLifetimeManager>();

            foreach (TLifetimeManager lifetimeManager in lifetimeManagers)
            {
                try
                {
                    lifetimeManager.RemoveValue();
                }
                catch { }
            }
        }
    }
}
